﻿using System;
using System.Windows;
using PSE.Deployment.ConfigurationManager.Controls.Validations;
using PSE.Deployment.SetupBase.Configuration;

namespace PSE.Deployment.ConfigurationManager.Controls
{
    /// <summary>
    /// UserControl que permite somente input de Inteiros
    /// </summary>
    public class Int32TextBox : BaseSimpleTextBox
    {
        public Int32TextBox()
        {
            this.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(_PreviewKeyDown);
            this.PreviewDrop += new System.Windows.DragEventHandler(_PreviewDrop);
            this.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            this.VerticalAlignment = System.Windows.VerticalAlignment.Center;

            DataObject.AddPastingHandler(this, new DataObjectPastingEventHandler(CheckPasteFormat));
        }

        public Int32TextBox(XmlTag tag)
            : this()
        {
            this.DataContext = tag;
            ConfigurationBinding bd = new ConfigurationBinding();
            this.SetBinding(Int32TextBox.TextProperty, bd);
            this.IsRequired = tag.IsRequired;
        }

        public Int32TextBox(XmlAttribute attribute)
            : this()
        {
            this.DataContext = attribute;
            ConfigurationBinding bd = new ConfigurationBinding();
            this.SetBinding(Int32TextBox.TextProperty, bd);
            this.IsRequired = attribute.IsRequired;
        }

        public Int32TextBox(RegistryValue reg)
            : this()
        {
            this.DataContext = reg;
            ConfigurationBinding bd = new ConfigurationBinding();
            this.SetBinding(Int32TextBox.TextProperty, bd);
            this.IsRequired = reg.IsRequired;
        }

        void _PreviewDrop(object sender, System.Windows.DragEventArgs e)
        {
            if (e.Data.GetData(typeof(string)) != null && !SpecializedControlsValidations.IsNumber((string)e.Data.GetData(typeof(string)), false))
                e.Handled = true;
        }

        void _PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (!SpecializedControlsValidations.IsNumber(e.Key, false))
                e.Handled = true;
        }

        void CheckPasteFormat(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetData(typeof(string)) != null && !SpecializedControlsValidations.IsNumber((string)e.DataObject.GetData(typeof(string)), false))
                e.CancelCommand();
        }

        protected override bool Validate()
        {
            return SpecializedControlsValidations.IsNumber(this.Text, true);
        }

        protected override ErrorMessage GetErrorMessage()
        {
            return ErrorMessage.InvalidURL;
        }
    }
}